package com.zhenming.mirror.common;

import com.zhenming.mirror.enums.ConfigEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigProperties {
    private static Logger logger = LoggerFactory.getLogger(ConfigProperties.class);

    private final static String configFileName = "config.properties";

    private static String IMAGEPATH;

    public static String getImagePath() {
        return IMAGEPATH;
    }

    public static final Properties props = new Properties();

    static {
        String configFile = System.getenv("CONFIG_SPACE") + "/smm/" + configFileName;

        InputStream in = null;
        File file;
        try {
            file = new File(configFile);
            if (file.exists()) {
                in = new FileInputStream(file);
                props.load(in);
            } else {
                logger.info("config.properties不存在");
            }
        } catch (IOException e) {
            logger.info("config.properties加载失败");
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        IMAGEPATH = ConfigProperties.getProperty(ConfigEnum.IMAGE_PATH);
        // 创建本地文件夹
        File imageFile = new File(IMAGEPATH);
        if (!imageFile.exists()) {
            imageFile.mkdirs();
        }
    }

    /**
     * 获取静态变量参数
     *
     * @param config
     * @return
     */
    public static String getProperty(ConfigEnum config) {
        return props.getProperty(config.getCode());
    }

    /**
     * 获取静态变量参数
     *
     * @param config
     * @param defValue
     * @return
     */
    public static String getProperty(ConfigEnum config, String defValue) {
        String value = props.getProperty(config.getCode());
        if (value == null) {
            return defValue;
        }
        return value;
    }

    public static Integer getPropertyInt(ConfigEnum constant) {
        String value = props.getProperty(constant.getCode());
        if (value == null) {
            logger.error("找不到该配置:" + constant.getCode());
            return null;
        }
        return Integer.valueOf(value);
    }

    public static Integer getPropertyInt(ConfigEnum constant, Integer defValue) {
        String value = props.getProperty(constant.getCode());
        if (value == null) {
            return defValue;
        }
        return Integer.valueOf(value);
    }

}
